package com.xzz.mybatis.generator.controller;

import com.xzz.mybatis.generator.bean.GeneratorRequestDTO;
import com.xzz.mybatis.generator.bean.entity.User;
import com.xzz.mybatis.generator.config.MyDataSourceConfig;
import com.xzz.mybatis.generator.config.MybatisPlusGeneratorConfig;
import com.xzz.mybatis.generator.service.GeneratorService;
import com.xzz.mybatis.generator.service.UserService;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author: hhz
 * @createDate: 2021-3-10
 */
@Controller
public class IndexController {

    @Resource
    private MyDataSourceConfig myDataSourceConfig;
    @Resource
    private UserService userService;
    @Resource
    private GeneratorService mybatisPlusGeneratorService;

    @RequestMapping("/index")
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView("index");
        modelAndView.addObject("dsCodes", myDataSourceConfig.getDatasource().keySet());
        return modelAndView;
    }

    @RequestMapping("/getUser")
    @ResponseBody
    public List<User> getUser() {
        return userService.getList();
    }

    @RequestMapping("/test")
    @ResponseBody
    public void test() {
        userService.test();
    }


    @PostMapping("/generator/code")
    @ResponseBody
    public Map generator(@RequestBody @Valid GeneratorRequestDTO requestDTO) throws IOException {

        //删除原有target下自动生成的代码
        File classFolder = new File(MybatisPlusGeneratorConfig.class.getResource("/").getFile());
        FileUtils.deleteDirectory(new File(classFolder.getParent() + "/src"));

        //模块名，表名转化成小写
        mybatisPlusGeneratorService.generateCodeFile(requestDTO.getDatabase(), requestDTO.getModel().toLowerCase(),
                requestDTO.getTable().toLowerCase());
        return new HashMap(1);
    }
}
